package com.chookss.home.audit.project;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.ReturnMoneyEntity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class ReturnMoneyRecordActivity extends BaseAct {
//已审批列表

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private ReturnMoneyRecordAdapter adapter;
    private List<ReturnMoneyEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private String groupCode = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_srlview_top);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        groupCode = getIntent().getStringExtra("groupCode");
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) smrRf.getLayoutParams();
        params.setMargins(0, Utils.dip2px(this, 12), 0, 0);
        smrRf.setLayoutParams(params);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new ReturnMoneyRecordAdapter(R.layout.item_reimbursement_record, this, list);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        commonTitleTxt.setText("回款记录");
        tvNone.setText("暂无回款记录");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("groupCode", groupCode);
        map.put("amtType", 16 + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ReturnMoneyEntity>>>() {
        }.getType(), null, Urls.selectItemAmtInfoList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ReturnMoneyEntity>>() {
            @Override
            public void onSuccess(List<ReturnMoneyEntity> data) {

                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                int old = list.size();
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class ReturnMoneyRecordAdapter extends BaseQuickAdapter<ReturnMoneyEntity, BaseViewHolderEx> {
        private Activity context;

        public ReturnMoneyRecordAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<ReturnMoneyEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ReturnMoneyEntity entity) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvTitleType = helper.getView(R.id.tvTitleType);
            TextView tvMoney = helper.getView(R.id.tvMoney);
            TextView tvPost = helper.getView(R.id.tvPost);
            TextView tvGroup = helper.getView(R.id.tvGroup);
            TextView tvInit = helper.getView(R.id.tvInit);
            LinearLayout llMoney = helper.getView(R.id.llMoney);
            LinearLayout llGroup = helper.getView(R.id.llGroup);
            LinearLayout llPost = helper.getView(R.id.llPost);
            tvTitle.setText(entity.getItemAmtName());
            llMoney.setVisibility(View.VISIBLE);
            tvMoney.setText("本次回款金额：" + ClearMoreZeroUtil.subZeroAndDot(entity.getAmt()) + "元");
            if (!Utils.isNull(entity.getRemark())) {
                tvInit.setText(entity.getRemark());
            } else {
                tvInit.setText("无");
            }
            if (Utils.isNull(entity.getGroupName())) {
                llGroup.setVisibility(View.GONE);
            } else {
                llGroup.setVisibility(View.VISIBLE);
                tvGroup.setText("所属项目组：" + entity.getGroupName());
            }
            if (Utils.isNull(entity.getOrgName())) {
                llPost.setVisibility(View.GONE);
            } else {
                llPost.setVisibility(View.VISIBLE);
                tvPost.setText("所属部门：" + entity.getOrgName());
            }

            if ("0".equals(entity.getAuditCd())) {
                tvTitleType.setText("审批中");
                tvTitleType.setTextColor(Color.parseColor("#FCA817"));
                tvTitleType.setBackgroundResource(R.drawable.shape_fca817_4_1f);
            } else if ("1".equals(entity.getAuditCd())) {
                tvTitleType.setText("已通过");
                tvTitleType.setTextColor(Color.parseColor("#44D3B3"));
                tvTitleType.setBackgroundResource(R.drawable.shape_44d3b3_4_2f);
            } else {
                if ("3".equals(entity.getAuditCd())) {
                    tvTitleType.setText("废弃");
                } else {
                    tvTitleType.setText("不通过");
                }
                tvTitleType.setTextColor(Color.parseColor("#F2434D"));
                tvTitleType.setBackgroundResource(R.drawable.shape_f2434d_4_2f);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(context, GroupDetailActivity.class);
                    intent.putExtra("repairCode", entity.getItemAmtCode());
                    intent.putExtra("type", Utils.changeNumber(entity.getAmtType()));
                    startActivity(intent);
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("RefreshGroupRecord")) {
                smrRf.autoRefresh();
            }
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick(R.id.common_title_back)
    public void onClick() {
        finish();
    }
}
